/* 配额导入-导入记录
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaImport\List\components\ImportRecordModal.tsx
 * @Date: 2021-08-19 12:02:50
 * @LastEditTime: 2021-09-07 10:12:16
 */
import React from 'react'
import { UdTable, UdFilter, columnRenders, http, UdDrawer, UdModal } from '@/lib'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { Select, TreeSelect, Tooltip, Tag, message } from 'antd'
import ImportRecordDetailModal from './ImportRecordDetailModal'
import quotaApis from '@/apis/AboutQuota'
import apis from '@/apis'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import _ from 'lodash'
import { handDownload } from '@/utils/methods'
const { TreeNode } = TreeSelect
const { Option } = Select

interface FileRecord {
  fileName: string
  fileUrl: string
  [key: string]: any
}
export default class ImportRecordModal extends React.Component<any> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: any[] = this.props.brandList //品牌公司
  private stageYearList: any[] = this.props.stageYearList //考核年度
  private FILE_TYPE_ENUM: any = {
    QUOTACHANGE: '客户标准配额',
    ACTUAL: '客户实际配额',
    ADJUSTMENT: '客户间配额调整',
    MODULATION: '客户配额调整',
  }
  private STATUS_ENUM: any = {
    AUDITING: '审核中',
    AUDITFAIL: '已拒绝',
    AUDITSUCC: '已通过',
  }
  state = {
    dataSource: [],
    searchValues: {},
    page: 1,
    size: 10,
    total: 0,
    loading: false,
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: (
          <UdSelect
            showSearch
            allowClear={false}
            options={this.brandList}
            onChange={value => {
              this.changeBrandCode(value)
            }}
          />
        ),
      },
      {
        id: 'prodBarcode',
        label: '配额品项',
        render: () => (
          <UdSelect
            showSearch
            options={this.state.prodBarCodeList}
            onChange={value => this.getManageImportStageName({ prodBarcode: value })}
          />
        ),
      },
      {
        id: 'belongAreaCode',
        label: '片区',
        render: () => (
          <TreeSelect showSearch treeNodeFilterProp="title">
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      {
        id: 'stageYear',
        label: '考核年度',
        render: () => (
          <UdSelect
            options={this.stageYearList}
            showSearch={true}
            optionFilterProp="children"
            onChange={value => this.getManageImportStageName({ stageYear: value })}
          />
        ),
      },
      {
        id: 'stageName',
        label: '考核阶段',
        render: () => <UdSelect options={this.state.stageNameList} showSearch={true} />,
      },
      {
        id: 'matter',
        label: '文件类型',
        render: () => (
          <Select>
            <Option value="QUOTACHANGE">客户标准配额</Option>
            <Option value="ACTUAL">客户实际配额</Option>
            <Option value="ADJUSTMENT">客户间配额调整</Option>
            <Option value="MODULATION">客户配额调整</Option>
          </Select>
        ),
      },
      {
        id: 'approvalStatus',
        label: '审批状态',
        render: () => (
          <Select>
            <Option value="AUDITING">审核中</Option>
            <Option value="AUDITFAIL">已拒绝</Option>
            <Option value="AUDITSUCC">已通过</Option>
          </Select>
        ),
      },
    ],
    prodBarCodeList: [], //配额品项
    treeDataList: [], //片区数据
    stageNameList: [], //考核阶段
  }
  columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '50px',
      render: (text, reoled, index) => index + 1,
    },
    { title: '文件名称', dataIndex: 'fileName', key: 'fileName', minWidth: '250px' },
    {
      title: '文件类型',
      key: 'matter',
      dataIndex: 'matter',
      render: (text, record) => {
        return this.FILE_TYPE_ENUM[record.matter] || ''
      },
      width: '120px',
    },
    { title: '品牌公司', dataIndex: 'brandName', key: 'brandName', width: 230 },
    { title: '配额品项', dataIndex: 'prodBarname', key: 'prodBarname', width: 150 },
    {
      title: '同步状态',
      key: 'isOrder',
      dataIndex: 'isOrder',
      render: (text, record) => {
        let obj = {
          1: '失败',
          0: '成功',
        }
        let state = obj[record.isOrder]
        //* 23-10-7 审核中不显示同步状态
        return record.isOrder != null && record.approvalStatus !== 'AUDITING' ? (
          <Tag color={text === 0 ? '#87d068' : '#f50'}>{state}</Tag>
        ) : (
          ''
        )
      },
      width: '100px',
    },
    { title: '考核年度', dataIndex: 'stageYear', key: 'stageYear', width: 110 },
    {
      title: '考核阶段',
      dataIndex: 'stageName',
      key: 'stageName',
      width: 200,
      render: (text, record) => {
        return (
          <Tooltip title={record.stageName}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.stageName}
            </div>
          </Tooltip>
        )
      },
    },

    {
      title: '配额有效期',
      dataIndex: 'quotaValidTime',
      key: 'quotaValidTime',
      type: 'inside',
      width: 110,
      render: (text, record) => {
        return (
          <Tooltip title={record.quotaValidTime}>
            <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.quotaValidTime}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '片区',
      dataIndex: 'belongAreaName',
      key: 'belongAreaName',
      width: 150,
      render: (text, record) => {
        return (
          <Tooltip title={record.belongAreaName}>
            <div style={{ width: '150px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.belongAreaName}
            </div>
          </Tooltip>
        )
      },
    },
    { title: '申请操作人', dataIndex: 'createName', key: 'createName', width: 110 },
    { title: '申请时间', dataIndex: 'createTime', key: 'createTime', width: 110 },
    {
      title: '审批状态',
      dataIndex: 'approvalStatus',
      key: 'approvalStatus',
      render: (text, record) => {
        return this.STATUS_ENUM[record.approvalStatus] || ''
      },
      width: 90,
    },
    { title: '审批时间', dataIndex: 'approvalTime', key: 'approvalTime', width: 110 },

    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      fixed: 'right' as 'right',
      width: 160,
      render: columnRenders.operate([
        {
          title: '查看',
          action: (text: any, record: any) => this.showImportRecordDetailModal(record),
        },
        {
          title: '重发',
          show: (text: any, record: any) => record['isOrder'] === 1 && record['approvalStatus'] === 'AUDITSUCC',
          action: (text: any, record: any) => this.handQuotaRetry(record),
        },
        {
          title: '预览',
          action: (text: any, record: any) => this.showFileViewModal(record),
        },
        {
          title: '下载',
          action: (text: any, record: any) => {
            handDownload(record.fileUrl)
          },
        },
      ]),
    },
  ]

  render() {
    return (
      <>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.state.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdTable
          rowKey="id"
          loading={this.state.loading}
          columns={this.columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </>
    )
  }

  private handQuotaRetry = (record: { tradeCode: string }) => {
    http.post(quotaApis.quotaRetry, { tradeCode: record.tradeCode, type: 0 }).then(res => {
      message.success('操作成功')
      this.handleSearch(this.filterForm.getFieldsValue())
    })
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  private changeBrandCode = (value: any) => {
    this.setState({ prodBarCodeList: [], treeDataList: [], stageNameList: [] }, () => {
      this.filterForm.setFieldsValue({ prodBarcode: undefined, stageName: undefined, belongAreaName: undefined })
    })

    Promise.all([this.getProdBarList(value), this.getAreaList(value)]).then(res => {
      this.setState(
        {
          prodBarCodeList: res[0],
          treeDataList: res[1],
        },
        () => {
          this.getManageImportStageName({ brandCode: value })
        }
      )
    })
  }

  private getManageImportStageName = (params?: any) => {
    this.setState({ stageNameList: [] }, () => {
      this.filterForm.setFieldsValue({ stageName: undefined })
    })

    let searchValues = this.filterForm.getFieldsValue()
    searchValues = { ...searchValues, ...params }
    if (searchValues.stageYear == null && searchValues.brandCode == null && searchValues.prodBarcode == null) {
      return false
    }
    http
      .get(quotaApis.getManageImportStageName, {
        params: {
          stageYear: searchValues.stageYear,
          brandCode: searchValues.brandCode,
          prodBarcode: searchValues.prodBarcode,
        },
      })
      .then(res => {
        const stageNameList = _.uniqBy(
          res.data?.map(item => ({ value: item.stageName, title: item.stageName })) || [],
          'value'
        )
        this.setState({ stageNameList })
      })
  }

  private getAreaList = (value: any) => {
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  public componentDidMount() {
    this.getRecordTableData()
    this.changeBrandCode(this.brandList[0].value)
  }

  private showFileViewModal = (record: FileRecord): void => {
    const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
    if (rex.test(record['fileUrl'])) {
      UdModal.open({
        title: record.fileName,
        width: '80%',
        bodyStyle: { padding: '0' },
        content: (
          <div style={{ height: '700px', overflow: 'hidden' }}>
            <iframe
              title={record.fileName}
              src={`https://view.officeapps.live.com/op/view.aspx?src=${record.fileUrl}`}
              width="100%"
              height="100%"
              frameBorder="0"
              style={{ border: 'none' }}
              seamless
            ></iframe>
          </div>
        ),
        footer: null,
      })
    } else {
      message.error('附件URL无效')
    }
  }

  private showImportRecordDetailModal = (record: FileRecord): void => {
    UdDrawer.open({
      title: '审批详情',
      width: '50%',
      content: <ImportRecordDetailModal record={record} />,
    })
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ searchValues: values, page: 1 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [], page: 1, total: 0, searchValues: form.getFieldsValue() }, () => {
      this.changeBrandCode(this.brandList[0].value)
      this.getRecordTableData()
    })
  }
  private getRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(quotaApis.getManageImportPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: { brandCode: this.brandList[0].value, ...this.state.searchValues },
      })
      const dataSource = list.data?.content

      this.setState({
        dataSource,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}
